#ifndef SGU_ZFILE_H
#define SGU_ZFILE_H

SGU_NS_BEGIN

/*! \brief File.
 *
 * Seekable regular file.
*/
class File : NoCopy, public UsedObj
{
	public:

	//!\brief File constructor.
	//!\sa See also <a href="man:open(2)">open(2)</a>
	File(
			const char * lpFileName,	//!< filename
			int flags,					//!< flags as in open(2)
			mode_t mode,				//!< mode_t as in open(2)
			t_destructretry drt = 0     //!< retry function for error in destructor
		);

	virtual ~File();
	
	size_t write(const void *, size_t) const;
	size_t read(void *, size_t) const;

	size_t getOfs() const;
	void setOfs(off_t pos, int whence = SEEK_SET) const;
	size_t getSize() const;
	void setSize(size_t) const;
	
	virtual operator int() const;

	private:
	int _fd;
	t_destructretry _drt;
};


class FileLock : NoCopy, public UsedObj
{
	public:
	FileLock(File & file, bool write, bool wait=false, t_destructretry drt = 0);
	virtual ~FileLock();
	
	private:
	t_destructretry _drt;
	File & _file;
	UserObj _file_use;
};


class FileMappingConstSegment : public ConstSegment
{
	public:
	FileMappingConstSegment(const char * filename, t_destructretry drt = 0);
	virtual ~FileMappingConstSegment();

	virtual size_t size() const;
	virtual const char * cptr() const;

	private:
	t_destructretry _drt;
	File _file;
	FileLock _lock;

	char * _ptr;
	size_t _size;
};

class FileMappingSegment : public Segment
{
	public:
	FileMappingSegment(const char * filename, t_destructretry drt = 0);
	virtual ~FileMappingSegment();

	virtual size_t size() const;
	virtual const char * cptr() const;
	virtual char * ptr() const;

	private:
	t_destructretry _drt;
	File _file;
	FileLock _lock;

	char * _ptr;
	size_t _size;
};

class FileMappingDynamicSegment : public DynamicSegment
{
	public:
	FileMappingDynamicSegment(const char * filename, bool create, mode_t mode, size_t growby, t_destructretry drt = 0);
	virtual ~FileMappingDynamicSegment();

	virtual size_t size() const;
	virtual const char * cptr() const;
	virtual char * ptr() const;
	
	virtual void resize(size_t);
	virtual void clear(size_t);
	virtual void clear();

	private:
	t_destructretry _drt;
	File _file;
	FileLock _lock;

	char * _ptr;
	size_t _size;
	size_t _truesize;
	size_t _growby;
	
	void map();
	void unmap();
	size_t roundup(size_t);
};



SGU_NS_END

#endif

